import lockfile from 'proper-lockfile';
import path from "path";
import { toolchain } from "../toolchain.js";
import { sendBuildFailureAlert } from './alert.js';

export interface ILockFile {
    file: 'buildlock' | 'i18nlock',
    tip: string
}

export const BuildLock: ILockFile = { file: 'buildlock', tip: '其他构建任务正在执行' };
export const I18NLock: ILockFile = { file: 'i18nlock', tip: '翻译任务正在执行' };

export async function checkOrLockWorkspace(lock: ILockFile): Promise<void> {
    const alllocks = [BuildLock, I18NLock];
    for (const lock of alllocks) {
        const lf = path.join(toolchain.params.workSpacePath, lock.file);
        const buildlockStatus = await lockfile.check(lf, { realpath: false });
        if (buildlockStatus) {
            await sendBuildFailureAlert('Workspace locked! Please wait! ' + lock.tip);
            process.exit(1);
        }
    }

    const lf = path.join(toolchain.params.workSpacePath, lock.file);
    toolchain.lockfile = lock;
    await lockfile.lock(lf, { realpath: false });
    console.log('build lock setup:', lf);
}

export async function unlockWorkspace(): Promise<void> {
    if (toolchain.lockfile != null) {
        const lf = path.join(toolchain.params.workSpacePath, toolchain.lockfile.file);
        await lockfile.unlock(lf, { realpath: false });
        console.log('build lock released');
    }
}
